#include <stdio.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>

#define TIMEOUT (5)
#define BUF_LEN (1024)

int main(int argc, char** argv)
{
    printf("Test using select to read STDIN. 5s timeout.\n");
    struct timeval tv;
    fd_set readfds;
    int ret;

    FD_ZERO(&readfds);
    FD_SET(STDIN_FILENO, &readfds);

    tv.tv_sec = TIMEOUT;
    tv.tv_usec = 0;

    ret = select(STDIN_FILENO + 1,
                 &readfds,
                 NULL,
                 NULL,
                 &tv);
    if (ret == -1)
    {
        // 发生错误的时候返回-1；
        perror("select");
        return 1;
    }
    else if (!ret)
    {
        // 超时的时候函数返回0
        printf("超时:经过了%d秒\n", TIMEOUT);
        return 0;
    }

    if(FD_ISSET(STDIN_FILENO, &readfds))
    {
        char buf[BUF_LEN + 1] = {0};
        int len;
        len = read(STDIN_FILENO, buf, BUF_LEN);
        if (len == -1)
        {
            perror("read");
            return 1;
        }

        if (len){
            buf[len] = '\0';
            printf("read: %s\n", buf);
            printf("over.\n");
            return 0;
        }
    }
    fprintf(stderr, "不应到这里，说明逻辑有问题。\n");
    return 1;

}
